package com.sendpo.zjx.sendpo.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.sendpo.zjx.sendpo.BuildConfig;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.net.HttpCode;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.services.AmapLocationService;
import com.sendpo.zjx.sendpo.table.User;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.shaohui.bottomdialog.BottomDialog;

/**
 * Created by Administrator on 2017/8/21.
 */

public class MyselfSubmitFabuActivity extends AppCompatActivity implements AMapLocationListener {
    public final int REQUEST_IMAGECOUNT = 1031;
    public final int REQUEST_CAMERA = 104;
    public final int REQUEST_CROP = 105;
    BottomDialog bottomDialog;
    public List<String> fileList = new ArrayList<>();
    File temp_cmera = null;

    @BindView(R.id.edit_text)
    EditText editText;
    @BindView(R.id.openupload_all)
    LinearLayout openuploadAll;
    @BindView(R.id.hsv)
    HorizontalScrollView hsv;
    @BindView(R.id.openupload_iv)
    ImageView openuploadIv;

    private Dialog loadingdialog,tagdialog;
    public AmapLocationService amapLocationService;
    public double userLongitude = 0;
    public double userLatitude = 0;
    public String userProvince = "";
    public String userCity = "";
    public String userArea = "";
    public String userAddress = "";
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_myselfsubmitthings_edit);
        ButterKnife.bind(this);
        Tools.initStatus(this, R.color.black);
        initComponent();
    }

    public void initComponent() {
        showOpenDialog();
        amapLocationService=new AmapLocationService(this);
        amapLocationService.setmLocationOption(getDefaultAmapLocationOptions());
        amapLocationService.registerListener(this);
        amapLocationService.start();
    }



    public AMapLocationClientOption getDefaultAmapLocationOptions(){
        AMapLocationClientOption mLocationOption=null;
        if(mLocationOption==null){
            mLocationOption = new AMapLocationClientOption();
            //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            mLocationOption.setLocationCacheEnable(true);
            mLocationOption.setOnceLocation(true);
            mLocationOption.setOnceLocationLatest(false);
            //设置是否返回地址信息（默认返回地址信息）
            mLocationOption.setNeedAddress(true);
            //设置是否强制刷新WIFI，默认为true，强制刷新。
            mLocationOption.setWifiScan(true);
            mLocationOption.setInterval(1000);
            //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
            mLocationOption.setHttpTimeOut(20000);
        }
        return  mLocationOption;
    }


    @OnClick({R.id.backbt, R.id.openupload_iv, R.id.submit_bt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.backbt:
                finish();
                break;
            case R.id.openupload_iv:
                if (fileList.size() >= 4) {
                    Toast.makeText(this.getApplicationContext(), "已有4张图片", Toast.LENGTH_SHORT).show();
                    return;
                }
                bottomDialog.show();
                break;

            case R.id.submit_bt:
                if (TextUtils.isEmpty(editText.getText().toString().trim())) {
                    Toast.makeText(this.getApplicationContext(), "内容不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
//                if (fileList.size() == 0) {
//                    Toast.makeText(this.getApplicationContext(), "图片至少一张", Toast.LENGTH_SHORT).show();
//                    return;
//                }

                submit(editText.getText().toString().trim());
                break;

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }

        switch (requestCode) {
            case REQUEST_IMAGECOUNT:
                Uri datauri = data.getData();
                final File finalFile1 = new File(getExternalCacheDir().getAbsolutePath() + "/" + UUID.randomUUID().toString().substring(0,10)+".png");;
                Glide.with(this)
                        .load(datauri)
                        .asBitmap()
                        .override(500, 500)
                       .placeholder(getResources().getColor(R.color.default_lightgray))
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                try {
                                    Bitmap bitmap=null;
                                    if(resource.getHeight()<500){
                                        bitmap= Tools.zoomBitmap(resource,resource.getWidth()/1,resource.getHeight()/1);
                                    }else if(resource.getHeight()<1000){
                                        bitmap= Tools.zoomBitmap(resource,resource.getWidth()/2,resource.getHeight()/2);
                                    }else {
                                        bitmap= Tools.zoomBitmap(resource,resource.getWidth()/3,resource.getHeight()/3);
                                    }
                                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(finalFile1));
                                    fileList.add(finalFile1.getPath());
                                    final View imgview = View.inflate(MyselfSubmitFabuActivity.this, R.layout.layout_uploadimg_layout, null);
                                    ImageView imgview_iv = imgview.findViewById(R.id.image);
                                    imgview_iv.setImageBitmap(BitmapFactory.decodeFile(finalFile1.getPath()));
                                    View imgview__delte = imgview.findViewById(R.id.delete_iv);
                                    imgview__delte.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                            openuploadAll.removeView(imgview);
                                            fileList.remove(finalFile1.getPath());
                                        }
                                    });
                                    openuploadAll.addView(imgview);
                                } catch (FileNotFoundException e) {
                                    e.printStackTrace();
                                }
                            }
                        });

                break;

            case REQUEST_CAMERA:
                Intent bgcamera = new Intent("com.android.camera.action.CROP");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    bgcamera.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    Uri contentUri = FileProvider.getUriForFile(MyselfSubmitFabuActivity.this, BuildConfig.APPLICATION_ID + ".fileProvider",temp_cmera);
                    bgcamera.setDataAndType(contentUri, "image/*");
                } else {
                    bgcamera.setDataAndType(Uri.fromFile(temp_cmera), "image/*");
                }
                bgcamera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(temp_cmera));
                bgcamera.putExtra("return-data", false);
                bgcamera.putExtra("scale", true);
                bgcamera.putExtra("outputFormat", Bitmap.CompressFormat.PNG);
                bgcamera.putExtra("noFaceDetection", true);
                //     bgcamera.putExtra("aspectX",son1);
                //     bgcamera.putExtra("aspectY",son1);
                bgcamera.putExtra("outputX", 500);
                bgcamera.putExtra("outputY", 500);
                startActivityForResult(bgcamera, REQUEST_CROP);
                break;

            case REQUEST_CROP:
                fileList.add(temp_cmera.getPath());
                Glide.with(this)
                        .load(temp_cmera.getPath())
                        .asBitmap()
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                Bitmap bitmap=null;
                                if(resource.getHeight()<500){
                                    bitmap= Tools.zoomBitmap(resource,resource.getWidth()/1,resource.getHeight()/1);
                                }else if(resource.getHeight()<1000){
                                    bitmap= Tools.zoomBitmap(resource,resource.getWidth()/2,resource.getHeight()/2);
                                }else {
                                    bitmap= Tools.zoomBitmap(resource,resource.getWidth()/3,resource.getHeight()/3);
                                }
                                try {
                                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(temp_cmera));
                                    final View camera_imgview = View.inflate(MyselfSubmitFabuActivity.this, R.layout.layout_uploadimg_layout, null);
                                    ImageView camera_imgview_iv = camera_imgview.findViewById(R.id.image);
                                    camera_imgview_iv.setImageBitmap(BitmapFactory.decodeFile(temp_cmera.getPath()));
                                    View camera_imgview__delte = camera_imgview.findViewById(R.id.delete_iv);
                                    final String t = temp_cmera.getPath();
                                    camera_imgview__delte.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                            openuploadAll.removeView(camera_imgview);
                                            fileList.remove(t);
                                            File delete = new File(t);
                                            delete.delete();
                                        }
                                    });
                                    openuploadAll.addView(camera_imgview);
                                } catch (FileNotFoundException e) {
                                    e.printStackTrace();
                                }
                            }
                        });

                break;
        }

    }

    public void showOpenDialog() {
        loadingdialog = new Dialog(this);
        loadingdialog.setContentView(R.layout.dialog_loading);
        loadingdialog.setCanceledOnTouchOutside(false);
        loadingdialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        bottomDialog = BottomDialog.create(getSupportFragmentManager());
        bottomDialog.setViewListener(new BottomDialog.ViewListener() {
            @Override
            public void bindView(View v) {
                v.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        bottomDialog.dismiss();
                    }
                });
                View camera = v.findViewById(R.id.camera);
                camera.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        temp_cmera = new File(getExternalCacheDir().getAbsolutePath()+"/" + UUID.randomUUID().toString().substring(0, 10) + ".jpg");
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        intent.putExtra("return-data", true);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                            Uri contentUri = FileProvider.getUriForFile(MyselfSubmitFabuActivity.this, BuildConfig.APPLICATION_ID + ".fileProvider",temp_cmera);
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
                        } else {
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(temp_cmera));
                        }
                        startActivityForResult(intent, REQUEST_CAMERA);
                        bottomDialog.dismiss();
                    }
                });
                View exit = v.findViewById(R.id.exit);
                exit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        bottomDialog.dismiss();
                    }
                });
                View imgcontent = v.findViewById(R.id.imgcontent);
                imgcontent.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
                        intent.setType("image/*");
                        intent.putExtra("return-data", true);
                        startActivityForResult(intent, REQUEST_IMAGECOUNT);
                        bottomDialog.dismiss();
                    }
                });
            }
        });
        bottomDialog.setLayoutRes(R.layout.dialog_uploadimg);
        bottomDialog.setDimAmount(0.5f);
        bottomDialog.setCancelOutside(true);
        bottomDialog.setTag("BottomDialog");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (fileList != null && fileList.size() != 0) {
            for (String file : fileList) {
                File file1 = new File(file);
                file1.delete();
            }
        }
    }

    public void submit(String userdynamicText){
        final List<User> userList = Xutils.queryAll(getApplication(), User.class);
        if (userList == null || userList.size() == 0) {
            return;
        }
        User user = userList.get(0);
        loadingdialog.show();
        RequestParams params=new RequestParams(HttpUrl.dynamicAdd);
        params.addParameter("userId",user.getUserId()+"");
        params.addParameter("userdynamicText",userdynamicText);
        params.addParameter("userCity",userCity);
        params.addParameter("userArea",userArea);
        params.addParameter("userLongitude",userLongitude);
        params.addParameter("userLatitude",userLatitude);
        if(fileList.size()!=0){
            for(String file:fileList){
                params.addParameter("files",new File(file));
            }
        }
        params.setCharset("UTF-8");
        params.setMultipart(true);
        Callback.Cancelable cancelable= x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                loadingdialog.dismiss();
                try {
                    JSONObject jsonObject=new JSONObject(result);
                    Toast.makeText(getApplicationContext(),jsonObject.getString("message"),Toast.LENGTH_SHORT).show();
                    switch (jsonObject.getInt("state")){
                        case HttpCode.SUCCESS:
                            setResult(RESULT_OK);
                            finish();
                            break;
                        case HttpCode.ERROR:
                            break;

                        case HttpCode.THROW:

                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                loadingdialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (amapLocationService == null || aMapLocation == null) {
            Toast.makeText(getApplicationContext(),"定位失败，请检查网络和手机权限或者是否打开GPS",Toast.LENGTH_SHORT).show();
            return;
        }
        userLongitude=aMapLocation.getLongitude();
        userLatitude=aMapLocation.getLatitude();
        userProvince=aMapLocation.getProvince();
        userCity=aMapLocation.getCity();
        userArea=aMapLocation.getDistrict();
        int index=aMapLocation.getAddress().lastIndexOf(userProvince+userCity+userArea);
        userAddress=aMapLocation.getAddress().substring(index+(userProvince+userCity+userArea).length(),aMapLocation.getAddress().length());
    }




}
